<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">活动编号</label>
        <el-input v-model="query.activityId" clearable placeholder="活动编号" style="width: 160px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">订单号</label>
        <el-input v-model="query.orderNo" clearable placeholder="订单号" style="width: 160px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">下单时间</label>
        <date-range-picker
          v-model="query.orderTime"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          class="date-item"

        />
        <label class="el-form-item-label">媒体编号</label>
        <el-input v-model="query.uid" clearable placeholder="媒体编号" style="width: 90px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <!--<label class="el-form-item-label">下单用户信息</label>
        <el-input v-model="query.orderUname" clearable placeholder="下单用户信息" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">手机号</label>
        <el-input v-model="query.phone" clearable placeholder="手机号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        -->
        <label class="el-form-item-label">报单匹配</label>
        <el-select v-model="query.pipei" clearable size="small" placeholder="是否匹配" class="filter-item" style="width: 100px"  @change="crud.toQuery">
          <el-option v-for="item in dict.yn" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>


        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission">
        <!-- 新增 -->
        <el-button
          slot="left"
          v-permission="['admin','order:add']"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-upload"
          @click="crud.toAdd"
        >导入订单
        </el-button>
        <!--  -->
        <el-button
          slot="left"
          v-permission="['admin','order:add']"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-upload"
          @click="tp()"
        >模板文件下载
        </el-button>
        <!--  -->
        <el-button
          slot="left"
          v-permission="['admin','order:add']"
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-upload"
          @click="settle(crud.selections)"
          :disabled="crud.selections.length === 0"
        >设置为已结算
        </el-button>
      </crudOperation>

      <!--表单组件-->
      <!--
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form1" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="活动编号">
            <el-input v-model="form.activityId" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="订单号">
            <el-input v-model="form.orderNo" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="类目">
            <el-input v-model="form.orderType" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="订单日期">
            <el-date-picker v-model="form.orderDate" type="datetime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="订单时间">
            <el-date-picker v-model="form.orderTime" type="datetime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="订单金额">
            <el-input v-model="form.orderAmt" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="订单状态">
            <el-input v-model="form.orderStatus" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="媒体编号">
            <el-input v-model="form.uid" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="下单用户信息">
            <el-input v-model="form.orderUname" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="手机号">
            <el-input v-model="form.phone" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker v-model="form.createTime" type="datetime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="最后更新时间">
            <el-date-picker v-model="form.lastUpdateTime" type="datetime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="返利方式">
            <el-select v-model="form.payType" filterable placeholder="请选择">
              <el-option
                v-for="item in dict.pay_type"
                :key="item.id"
                :label="item.label"
                :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="支付账号">
            <el-input v-model="form.payNo" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="报单匹配">
            <el-radio v-model="form.pipei" v-for="item in dict.yn" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
          </el-form-item>
          <el-form-item label="备注1">
            <el-input v-model="form.extra1" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="备注2">
            <el-input v-model="form.extra2" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>-->

      <!--表单组件-->
      <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.add ? '导入订单' : '编辑订单'" width="500px">
        <el-form ref="form" :model="form" size="small" label-width="80px">
          <el-form-item label="文件名"  style="display: none;">
            <el-input v-model="form.name" style="width: 370px;display: none;" />
          </el-form-item>
          <!--   上传文件   -->
          <el-form-item v-if="crud.status.add" label="上传">
            <el-upload
              ref="upload"
              :limit="1"
              :before-upload="beforeUpload"
              :auto-upload="false"
              :headers="headers"
              :on-success="handleSuccess"
              :on-error="handleError"
              :action="'http://8.135.117.242:8083/api/order/importOrder?name=' + form.name"
            >
              <div class="eladmin-upload"><i class="el-icon-upload" /> 添加文件</div>
              <div slot="tip" class="el-upload__tip">可上传任意格式文件，且不超过100M</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button v-if="crud.status.add" :loading="loading" type="primary" @click="upload">确认</el-button>
          <el-button v-else :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <comp v-if="crud.update">
      <label class="el-form-item-label" style="color: red;">
        订单总计：{{crud.totalData.dc}}笔（{{ _fenToYuan('','',crud.totalData.da) }}元）&#12288;&#12288;
        差价总额：{{ _fenToYuan('','',crud.totalData.ca) }}元&#12288;&#12288;
        已跟单：{{crud.totalData.pc}}笔（{{ _fenToYuan('','',crud.totalData.pa) }}元）&#12288;&#12288;
        已结算：{{crud.totalData.sc}}笔（{{ _fenToYuan('','',crud.totalData.sa) }}元）&#12288;&#12288;
        待结算：{{ _fenToYuan('','',crud.totalData.dsa) }}元&#12288;&#12288;
      </label>
      </comp>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;"
                @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" :selectable="checkboxT"  width="55" />
        <el-table-column prop="id" label="id" />
        <el-table-column prop="activityId" label="活动编号" />
        <el-table-column prop="orderNo" label="订单号" />
        <!--<el-table-column prop="orderType" label="类目" />-->
        <!--<el-table-column prop="orderDate" label="订单日期" />-->
        <el-table-column prop="orderTime" label="订单时间" />
        <el-table-column prop="orderAmt" label="订单金额（元）"  :formatter="_fenToYuan" />
        <el-table-column prop="orderCount" label="订单数量" />
        <el-table-column prop="saleAmt" label="售价"  :formatter="_fenToYuan" />
        <el-table-column label="差价">
          <template slot-scope="scope">
            {{ chajia(scope) }}
          </template>
        </el-table-column>
        <el-table-column prop="orderStatus" label="订单状态" />
        <el-table-column prop="pipei" label="报单匹配">
          <template slot-scope="scope">
            {{ dict.label.yn[scope.row.pipei] }}
          </template>
        </el-table-column>
        <el-table-column prop="uid" label="媒体编号" />
        <el-table-column prop="settleStatus" label="是否结算">
          <template slot-scope="scope">
            {{ dict.label.yn[scope.row.settleStatus] }}
          </template>
        </el-table-column>
        <el-table-column prop="settleAmt" label="结算金额（元）"  :formatter="_fenToYuan" />
        <el-table-column prop="orderUname" label="微信号" />
        <el-table-column prop="kddh" label="快递单号" />
        <!--<el-table-column prop="phone" label="手机号" />-->
        <!--<el-table-column prop="createTime" label="创建时间" />-->
        <!--<el-table-column prop="lastUpdateTime" label="最后更新时间" />-->
        <el-table-column prop="payType" label="支付方式">
          <template slot-scope="scope">
            {{ dict.label.pay_type[scope.row.payType] }}
          </template>
        </el-table-column>
        <el-table-column prop="payNo" label="支付账号" />

        <el-table-column prop="extra1" label="备注" />
        <!--<el-table-column prop="extra2" label="备注2" />-->
        <el-table-column v-if="checkPer(['admin','order:edit','order:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.settleStatus!=='1'">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudOrder, { tpfile } from '@/api/order/order'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import DateRangePicker from '@/components/DateRangePicker'
import { getToken } from '@/utils/auth'
import request from "@/utils/request"
import momennt from "moment"
import {downloadFile} from "@/utils"


const defaultForm = { id: null, name: '' }

export default {
  name: 'OrderList',
  components: { pagination, crudOperation, rrOperation, udOperation, DateRangePicker },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['pay_type', 'yn', 'ftype'],
  cruds() {
    return CRUD({ title: 'order', url: 'api/order', idField: 'id', sort: 'id,desc', crudMethod: { ...crudOrder }})
  },
  data() {
    return {
      delAllLoading: false,
      loading: false,
      ndate: '2021-09-21 00:00:00',
      headers: { 'Authorization': getToken() },
      permission: {
        add: ['admin', 'order:add'],
        edit: ['11admin', 'order:edit1'],
        del: ['admin', 'order:del']
      },
      rules: {
        id: [
          { required: true, message: 'id不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'activityId', display_name: '活动编号' },
        { key: 'orderNo', display_name: '订单号' },
        { key: 'uid', display_name: '媒体编号' },
        { key: 'orderUname', display_name: '下单用户信息' },
        { key: 'phone', display_name: '手机号' },
        { key: 'pipei', display_name: '报单匹配' },
        { key: 'extra1', display_name: '备注1' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  created() {
    this.crud.optShow.add = false
  },
  mounted() {

   //this.crud.query.orderTime = [moment("YYYY-MM-DD") + " 00:00:00",moment("YYYY-MM-DD")+ " 23:59:59"];
  },
  methods: {
    // 上传文件
    upload() {
      this.$refs.upload.submit()
    },
    tp() {
      tpfile()
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.form.name = file.name
      return isLt2M
    },
    handleSuccess(response, file, fileList) {
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.$refs.upload.clearFiles()
      this.crud.status.add = CRUD.STATUS.NORMAL
      this.crud.resetForm()
      this.crud.toQuery()
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    _fenToYuan(row, col, cellValue) {
      if (typeof cellValue === 'undefined' || cellValue === null || cellValue === '') {
        return ''
      } else {
        var num = Number(cellValue)
        if (!num) {
          return num + ''
        } else {
          num = Math.round((num) * 100) / 10000
          num = num.toFixed(2)
          num += ''
          var reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g
          return num.replace(reg, '$1,')
        }
      }
    },
    zoo(cellValue) {
      if (typeof cellValue === 'undefined' || cellValue === null || cellValue === '') {
        return '0'
      } else {
        var num = Number(cellValue)
        return num
      }
    },
    chajia(scope) {
      if (typeof scope.row.saleAmt === 'undefined' || scope.row.saleAmt === null || scope.row.saleAmt === '') {
        return ''
      }
      if (typeof scope.row.orderAmt === 'undefined' || scope.row.orderAmt === null || scope.row.orderAmt === '') {
        return ''
      }
      return this._fenToYuan('', '', this.zoo(scope.row.orderAmt) - this.zoo(scope.row.saleAmt))
    },
    checkboxT(row, rowIndex) {
      return row.settleStatus !== '1'
    },
    settle(datas) {
      this.$confirm(`确认结算选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        if (datas instanceof Array) {
          datas.forEach(val => {
            ids.push(val['id'])
          })
        }
       request({
          url: 'api/order/settle',
          method: 'post',
          data: ids
        }).then(() => {
         this.$notify({
           title: '结算成功',
           type: 'success',
           duration: 2500
         })
         this.crud.toQuery()
       })

      }).catch(() => {
      })
    }
  }
}
</script>

<style scoped>

</style>
